package com.zliblike_platform.controller;

import com.zliblike_platform.dto.BookListDTO;
import com.zliblike_platform.dto.BookListItemDTO;
import com.zliblike_platform.service.BookListService;
import com.zliblike_platform.vo.BookListItemVO;
import com.zliblike_platform.vo.BookListVO;
import com.zliblike_platform.vo.PageResult;
import com.zliblike_platform.vo.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 书单控制器
 */
@RestController
@RequestMapping("/api/book-lists")
public class BookListController {

    @Autowired
    private BookListService bookListService;
    
    /**
     * 创建书单
     */
    @PostMapping
    public ResponseResult<Long> createBookList(@RequestBody BookListDTO bookListDTO) {
        // 获取当前用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long userId = Long.parseLong(authentication.getName());
        
        // 创建书单
        Long listId = bookListService.createBookList(userId, bookListDTO);
        
        if (listId != null) {
            return ResponseResult.success("书单创建成功", listId);
        } else {
            return ResponseResult.fail(5001, "书单创建失败");
        }
    }
    
    /**
     * 更新书单信息
     */
    @PutMapping("/{listId}")
    public ResponseResult<Boolean> updateBookList(
            @PathVariable Long listId,
            @RequestBody BookListDTO bookListDTO) {
        // 获取当前用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long userId = Long.parseLong(authentication.getName());
        
        // 更新书单
        boolean success = bookListService.updateBookList(userId, listId, bookListDTO);
        
        if (success) {
            return ResponseResult.success("书单更新成功", true);
        } else {
            return ResponseResult.fail(5002, "书单更新失败，可能不存在或无权限");
        }
    }
    
    /**
     * 获取书单详情
     */
    @GetMapping("/{listId}")
    public ResponseResult<BookListVO> getBookListDetail(@PathVariable Long listId) {
        // 获取当前用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long userId = Long.parseLong(authentication.getName());
        
        // 查询书单详情
        BookListVO bookList = bookListService.getBookListDetail(listId, userId);
        
        if (bookList != null) {
            return ResponseResult.success(bookList);
        } else {
            return ResponseResult.fail(5003, "书单不存在或无权查看");
        }
    }
    
    /**
     * 获取书单中的书籍列表
     */
    @GetMapping("/{listId}/books")
    public ResponseResult<List<BookListItemVO>> getBookListItems(@PathVariable Long listId) {
        // 获取当前用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long userId = Long.parseLong(authentication.getName());
        
        // 先检查用户是否有权查看该书单
        BookListVO bookList = bookListService.getBookListDetail(listId, userId);
        if (bookList == null) {
            return ResponseResult.fail(5004, "书单不存在或无权查看");
        }
        
        // 查询书单中的书籍
        List<BookListItemVO> items = bookListService.getBookListItems(listId);
        
        return ResponseResult.success(items);
    }
    
    /**
     * 添加书籍到书单
     */
    @PostMapping("/{listId}/books")
    public ResponseResult<Long> addBookToList(
            @PathVariable Long listId,
            @RequestBody BookListItemDTO itemDTO) {
        // 获取当前用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long userId = Long.parseLong(authentication.getName());
        
        // 添加书籍到书单
        Long itemId = bookListService.addBookToList(userId, listId, itemDTO);
        
        if (itemId != null) {
            return ResponseResult.success("书籍添加成功", itemId);
        } else {
            return ResponseResult.fail(5005, "书籍添加失败，可能书单不存在、无权限或书籍已在书单中");
        }
    }
    
    /**
     * 从书单中移除书籍
     */
    @DeleteMapping("/{listId}/books/{itemId}")
    public ResponseResult<Boolean> removeBookFromList(
            @PathVariable Long listId,
            @PathVariable Long itemId) {
        // 获取当前用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long userId = Long.parseLong(authentication.getName());
        
        // 从书单中移除书籍
        boolean success = bookListService.removeBookFromList(userId, listId, itemId);
        
        if (success) {
            return ResponseResult.success("书籍移除成功", true);
        } else {
            return ResponseResult.fail(5006, "书籍移除失败，可能不存在或无权限");
        }
    }
    
    /**
     * 更新书单中的书籍备注
     */
    @PutMapping("/{listId}/books/{itemId}/note")
    public ResponseResult<Boolean> updateBookNote(
            @PathVariable Long listId,
            @PathVariable Long itemId,
            @RequestBody String note) {
        // 获取当前用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long userId = Long.parseLong(authentication.getName());
        
        // 更新书籍备注
        boolean success = bookListService.updateBookNote(userId, listId, itemId, note);
        
        if (success) {
            return ResponseResult.success("备注更新成功", true);
        } else {
            return ResponseResult.fail(5007, "备注更新失败，可能不存在或无权限");
        }
    }
    
    /**
     * 获取公开书单列表（分页）
     */
    @GetMapping("/public")
    public ResponseResult<PageResult<BookListVO>> getPublicBookLists(
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer size) {
        
        // 查询公开书单列表
        PageResult<BookListVO> result = bookListService.getPublicBookLists(page, size);
        
        return ResponseResult.success(result);
    }
    
    /**
     * 获取当前用户的书单列表（分页）
     */
    @GetMapping("/my")
    public ResponseResult<PageResult<BookListVO>> getMyBookLists(
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer size) {
        
        // 获取当前用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long userId = Long.parseLong(authentication.getName());
        
        // 查询用户的书单列表
        PageResult<BookListVO> result = bookListService.getUserBookLists(userId, page, size);
        
        return ResponseResult.success(result);
    }
    
    /**
     * 获取指定用户的公开书单列表（分页）
     */
    @GetMapping("/user/{userId}")
    public ResponseResult<PageResult<BookListVO>> getUserBookLists(
            @PathVariable Long userId,
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer size) {
        
        // 查询用户的书单列表
        PageResult<BookListVO> result = bookListService.getUserBookLists(userId, page, size);
        
        return ResponseResult.success(result);
    }
    
    /**
     * 删除书单
     */
    @DeleteMapping("/{listId}")
    public ResponseResult<Boolean> deleteBookList(@PathVariable Long listId) {
        // 获取当前用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long userId = Long.parseLong(authentication.getName());
        
        // 删除书单
        boolean success = bookListService.deleteBookList(userId, listId);
        
        if (success) {
            return ResponseResult.success("书单删除成功", true);
        } else {
            return ResponseResult.fail(5008, "书单删除失败，可能不存在或无权限");
        }
    }
} 